package com.ss.tmall.service.impl;

import com.ss.tmall.mapper.OrderItemMapper;
import com.ss.tmall.mapper.OrderMapper;
import com.ss.tmall.pojo.Order;
import com.ss.tmall.pojo.OrderItem;
import com.ss.tmall.pojo.OrderItemExample;
import com.ss.tmall.pojo.Product;
import com.ss.tmall.service.OrderItemService;
import com.ss.tmall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: ShengShuai
 * @Description:
 * @Date: Created in 上午 1:22  2017/12/30 0030
 * @Modified By:
 */
@Service
public class OrderItemServiceImpl implements OrderItemService {
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    ProductService productService;
    @Override
    public  void  add(OrderItem orderItem){
orderItemMapper.insert(orderItem);
    }
    @Override
    public  void  delete(int id){
        orderItemMapper.selectByPrimaryKey(id);
    }
    @Override
    public  void  update(OrderItem orderItem){
        orderItemMapper.updateByPrimaryKeySelective(orderItem);
    }
    @Override
    public  OrderItem get(int id){

        OrderItem result= orderItemMapper.selectByPrimaryKey(id);
        setProduct(result);
        return  result;
    }

    private void setProduct(OrderItem oi) {
        Product product =productService.get(oi.getPid());
        oi.setProduct(product);
    }
    public  void  setProduct(List<OrderItem> ois){
        for (OrderItem o:ois) {
            setProduct(o);
        }
    }
@Override
    public List<OrderItem> list(){
        OrderItemExample example =new OrderItemExample();
        example.setOrderByClause("id desc");
        return orderItemMapper.selectByExample(example);

    }
    @Override
    public  void  fill(List<Order> os){
        for (Order o: os) {
         fill(o);
        }
    }
    @Override
    public  void  fill(Order o){
        OrderItemExample example = new OrderItemExample();
        example.createCriteria().andIdEqualTo(o.getId());
        example.setOrderByClause("id desc");
        List<OrderItem> ois = orderItemMapper.selectByExample(example);
        setProduct(ois);
        float total=0;
        int totalNumber=0;
        for (OrderItem oi:ois) {
                total+=oi.getNumber()*oi.getProduct().getPromotePrice();
            totalNumber+=oi.getNumber();
        }
        o.setTotal(total);
        o.setTotaoNumber(totalNumber);
        o.setOrderItems(ois);
    }

}
